<!-- 动态表单渲染组件 -->
<template>
  <!-- 子集信息 -->
  <div
    v-if="!componentType || componentType === 'CONTAINER'"
    class="vecational-work"
  >
    <div class="noType">
      <!-- 控件信息 -->
      <a-form-item
        :label="labelName"
        field="oneValue"
        show-colon
        :rules="[
          {
            required: modelData.required == 1 ? true : false,
            validator
          }
        ]"
      >
        <FormDesignRender
          :component-type="componentType"
          v-model:values="modelData.values"
          :props="modelData.props"
          :review="props.review"
          v-model:data="modelData"
        />
      </a-form-item>
    </div>
  </div>
  <!-- 控件信息 -->
  <a-form-item
    v-else
    :label="labelName"
    field="oneValue"
    show-colon
    :rules="[
      {
        required: modelData.required == 1 ? true : false,
        validator
      }
    ]"
  >
    <FormDesignRender
      :component-type="componentType"
      v-model:values="modelData.values"
      :props="modelData.props"
      :review="props.review"
      v-model:data="modelData"
    />
  </a-form-item>
</template>
<script setup lang="ts">
import useForm from '@/hooks/useForm';
import FormDesignRender from './FormDesignRender.vue';
import useControlFormStore from '@/store/controlForm';
import { useVModel } from '@vueuse/core';

const props = withDefaults(
  //参数说明
  defineProps<{
    data?: any;
    regex?: {
      [name: string]: {
        role: any;
        name: any;
      };
    };
    isSub?: boolean;
    review?: boolean;
  }>(),
  {
    isSub: false,
    review: false
  }
);
const emits = defineEmits(['update:values', 'update:data']);
const modelData = useVModel(props, 'data', emits);
const controlFormStore = useControlFormStore();
const componentType = computed(() => {
  console.log(
    'controlFormStore.fieldNames.componentType',
    controlFormStore.fieldNames.componentType
  );

  if (!props?.data) return '错误';
  return props.data[controlFormStore.fieldNames.componentType];
});
const labelName = computed(() => {
  if (!props?.data) return '错误';
  return props.data[controlFormStore.fieldNames.labelName];
});
const { selectItem, ctlSelectedIndex, remove, formItemClick, change } =
  useForm();

//字段动态校验
const validator = (value: any, callback: any) => {
  const { values, required, regex } = modelData.value;

  if (componentType.value === 'TEXT') {
    //单行输入框
    const { validate } = modelData.value.props;
    if (required && !values[0]) return callback('请输入' + labelName.value);
    if (!validate) return callback();

    if (regex) {
      const roleItem = regex[validate];
      const checkVal = roleItem.role.test(values[0]);
      if (!checkVal) {
        return callback(new Error('请输入正确的' + roleItem.name));
      }
    }
  } else if (componentType.value === 'TEXT_AREA') {
    //多行输入框
    if (required && !values[0]) return callback('请输入' + labelName.value);
  }
  callback();
};
</script>
<style lang="less" scoped></style>
